package com.ar4j.bench.hibernate.service;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;

import com.ar4j.bench.common.domain.IItem;
import com.ar4j.bench.common.service.IItemService;
import com.ar4j.bench.hibernate.domain.Item;

/**
 * An item service implemented using the Hibernate library
 */
@Service
public class ItemHibernateService extends HibernateDaoSupport implements IItemService {
  
  @Autowired
  public void setAutowiredSessionFactory(SessionFactory factory) {
    super.setSessionFactory(factory);
  }
  
  @Override
  public Long addItem(IItem item) {
    getHibernateTemplate().save(item);
    return item.getId();
  }

  @Override
  public IItem findById(Long id) {
    return getHibernateTemplate().get(Item.class, id);
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<IItem> findByProductId(Long productId) {
    return getHibernateTemplate().find("from Item i where i.product.id = ?", productId);
  }

  @Override
  public void removeById(Long id) {
    getHibernateTemplate().delete(findById(id));
  }

  @Override
  public void updateItem(IItem item) {
    getHibernateTemplate().update(item);
  }

}
